use eframe::egui;
use eframe::egui::{Align, Layout, Ui};
use egui_extras::{Column, TableBuilder};

use crate::components::MyApp;

impl MyApp {
    pub fn ui_user_list(&mut self, ui: &mut Ui) {
        let text_height = egui::TextStyle::Body
            .resolve(ui.style())
            .size
            .max(ui.spacing().interact_size.y);

        if ui.button("刷新列表").clicked() {
            let vec = self.db.users();
            println!("users:{vec:?}");
            self.users = vec;
        }

        ui.separator();

        self.renderer_table(ui, text_height);
    }

    fn renderer_table(&mut self, ui: &mut Ui, text_height: f32) {
        let table = TableBuilder::new(ui)
            //条纹
            .striped(true)
            //大小可调整
            .resizable(false)
            //元素水平方向从左到右排列
            //垂直方向居中
            .cell_layout(Layout::left_to_right(Align::Center))
            //列宽自动缩放
            .column(Column::auto())
            .column(Column::auto())
            .column(Column::auto())
            ;

        table.header(20.0, |mut header| {
            header.col(|ui| { ui.strong("id"); });
            header.col(|ui| { ui.strong("姓名"); });
            header.col(|ui| { ui.strong("地址"); });
        }).body(|mut body| {
            for u in &self.users {
                body.row(text_height, |mut r| {
                    r.col(|ui| { ui.label(u.id.to_string()); });
                    r.col(|ui| { ui.label(u.name.to_string()); });
                    r.col(|ui| {
                        let address = u.address.clone().unwrap_or("".to_string());
                        ui.label(address);
                    });
                });
            }
        });
    }
}